<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>商品详情页</title>
    <link href="css/bootstrap.css" rel="stylesheet">
    <link href="fonts/glyphicons-halflings-regular.woff2">
</head>
<style>
    .container2 {
        display: flex;
        align-items: center;
        justify-content: center;
    }
</style>
<body>
<div id="top"></div>
<div class="outer-container">
</div>

<script type="text/javascript" src="js/jquery-3.6.4.js"></script>
<script src="js/bootstrap.min.js"></script>
<script type="text/javascript">
    $(function () {
        $("#top").load("top.html")
        const searchParams = new URLSearchParams(location.search);
        // 获取商品id
        const pId = searchParams.get("pId");
        $.ajax({
            url: "/PDD/product?method=detail&pId=" + pId,
            type: "POST",
            dataType: 'json',
            success: function (result) {
                let data = result.data[0]
                let price = data.price
                let html = `
  <div class="container">
    <div class="row">
      <div class="col-xs-6 col-md-6" style="margin-top: 7.5%">
        <a href="#" class="thumbnail">
          <img src="image/${data.pImage}" width="560" height="560"  alt="商品图片" />
        </a>
      </div>
      <div class="col-xs-6 col-md-6" style="margin-top: 1%">
        <div class="panel panel-default" style="height: 560px">
          <div class="panel-heading">
          <div class="form-group">商品详情 &nbsp;&nbsp;<button class="btn btn-danger" id="favorite" ></button></div>
          </div>
          <div class="panel-body">
            <h3>产品名称:<small>${data.pName}</small></h3>
            <div style="margin-left: 10px;">
              <p>市场价格:&nbsp;&nbsp;&nbsp;<span class="text-danger" style="font-size: 15px;">${data.price.toFixed(2)}</span>&nbsp;&nbsp;&nbsp;<span class="glyphicon glyphicon-yen"></span></p>
              <p>销量:&nbsp;&nbsp;&nbsp;${data.sales}</p>
              <p>评分:&nbsp;&nbsp;&nbsp;${data.pScore}</p>
              <p>库存:&nbsp;&nbsp;&nbsp;${data.stock}</p>
              <p>详细介绍:</p>
              <p>&nbsp;&nbsp;${data.pInfo}</p>
              <a href="javascript:void(0)" id="addCart" class="btn btn-warning">加入购物车&nbsp;&nbsp;&nbsp;<span class="glyphicon glyphicon-shopping-cart"></span></a>&nbsp;&nbsp;&nbsp;
              <button class="btn btn-danger" id="buy">购买</button>
              <span id="getDiscount"><div id="myPopover"></div></span>
              <span id="invite"></span>
              <div class="container2">
              请选择您的购买数量:
              <div class="input-group">
                       <span class="input-group-btn">
                           <button id="substract" class="btn btn-default" type="button">-</button>
                       </span>
                       <input type="text" class="form-control" id="num" value="1" readonly="readonly" style="width:40px">
                       <span class="input-group-btn">
                           <button id="add" class="btn btn-default" type="button">+</button>
                       </span>
               </div>
               <div id="tips" class="btn btn-default"></div>
               </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>`;
                $(".outer-container").html(html)
                //ajax请求商品优惠券情况
                $.ajax({
                    url:"/PDD/product?method=showDiscount&pId="+pId,
                    dataType:"json",
                    success:function (data){
                        let discounts=data.data
                        if(discounts!=null) {
                            //$("#getDiscount").html("<button id='get' class=\"btn btn-group\">领取优惠券</button>")
                            let html2 = "!!!该商品当前优惠情况!!!!"
                            for (let i = 0; i < discounts.length; i++) {
                                let discount = discounts[i]
                                html2 += `<div><span>${discount.dName}</span>:<span>${discount.dAmount}张</span></div>`
                            }
                            $("#tips").html(html2)
                        }
                        //发送ajax请求用户使用优惠券的情况(是否使用过)
                        $.ajax({
                            url:"/PDD/product?method=showUsageOfDiscount",
                            data:{
                                "pId":pId
                            },
                            dataType:"json",
                            success:function (data){
                                let usage=data.data
                                if(discounts!=null&&usage==null){
                                    let html1=`<button id='get' class="btn btn-group">领取优惠券</button><div id="myPopover">`
                                    for (let i = 0; i < discounts.length; i++) {
                                        let discount = discounts[i]
                                        html1 += `<button id="discount${i}" type="button" class="btn btn-group">${discount.dName}</button>`
                                    }
                                    html1+=`</div>`
                                    $("#getDiscount").html(html1)
                                    let myPopover=$("#myPopover")
                                    let getBtn=$("#get")
                                    myPopover.hide();  // 隐藏弹出框
                                    getBtn.click(function() {
                                        let position = getBtn.offset();  // 获取按钮位置
                                        let posX = position.left; // 计算弹出框位置的 X 坐标
                                        let posY = position.top+25;  // 计算弹出框位置的 Y 坐标
                                        myPopover.css({top: posY, left: posX}).show(); // 设定弹出框位置并显示它
                                    });
                                    $(document).mouseup(function(e) {  // 点击页面其它部分时，隐藏弹出框
                                        let container = myPopover;
                                        if (!container.is(e.target) && container.has(e.target).length === 0) {
                                            container.hide();
                                        }
                                    });
                                    for (let i = 0; i < discounts.length; i++) {
                                        let discount = discounts[i]
                                        $("#discount"+i).click(function (){
                                            //发送ajax请求 后台添加用户使用优惠券的记录
                                            $.ajax({
                                                url:"/PDD/product?method=addUsageOfDiscount",
                                                data:{
                                                    "pId":pId,
                                                    "tId":discount.tId,
                                                    "dAmount":1,
                                                    "dState":0
                                                },
                                                dataType:"json",
                                                success:function (){
                                                    location.reload()
                                                }
                                            })
                                            //发送ajax请求 修改优惠券数量(需要pid tid dAmount参数)
                                            $.ajax({
                                                url:"/PDD/product?method=modifyDiscount",
                                                data:{
                                                    "pId":pId,
                                                    "tId":discount.tId,
                                                    "dAmount":discount.dAmount,
                                                    "change":"-1"
                                                },
                                                dataType:"json",
                                            })
                                        })
                                    }
                                }else if(discounts!=null&&usage!=null){
                                    $("#getDiscount").html(`<button id='get' class="btn btn-group">您近期已领取过优惠券</button>`)
                                }
                            }
                        })
                        //发送ajax请求查询是否领取半价优惠
                        $.ajax({
                            url:"/PDD/product?method=showInviteDetail",
                            data:{
                                "pId":pId,
                            },
                            dataType:"json",
                            success:function (iData){
                                //后台无数据 表明还没参与邀请新人活动
                                if(iData.data==null){
                                    $("#invite").html(`<a href="invite.html?pId=${pId}&refundCount=${price.toFixed(2)}" class="btn btn-group">邀请新用户可得半价优惠券!</a>`)
                                }else{
                                    //后台有数据
                                    let inviteDetail=iData.data[0]
                                    //如果邀请码状态为0 当前时间与数据库存储截止时间比对 看是否有效 无效就修改状态
                                    if(inviteDetail.codeState===0) {
                                        $.ajax({
                                            url: "/PDD/product?method=isInviteInValidTime",
                                            data:{
                                                "inviteCode":inviteDetail.inviteCode
                                            },
                                            dataType:"json",
                                        })
                                    }
                                    if(inviteDetail.codeState===0){
                                        //邀请码未生效
                                        $("#invite").html(`<button id='join' class="btn btn-group">邀请码未生效</button><div id="myPopover2">${inviteDetail.inviteCode}</div>`)
                                        let joinBtn=$("#join")
                                        let myPopover2=$("#myPopover2")
                                        myPopover2.hide()
                                        joinBtn.click(function (){
                                            showInviteCode(joinBtn,myPopover2)
                                        })
                                    }else if(inviteDetail.codeState===1){
                                        //邀请码已生效
                                        $("#invite").html(`<button id='join' class="btn btn-group">邀请码已生效</button><div id="myPopover2">${inviteDetail.inviteCode}</div>`)
                                        let joinBtn=$("#join")
                                        let myPopover2=$("#myPopover2")
                                        myPopover2.hide()
                                        joinBtn.click(function (){
                                            showInviteCode(joinBtn,myPopover2)
                                        })
                                    }else{
                                        $("#invite").html(`<button id='join' class="btn btn-group">邀请码已失效</button><div id="myPopover2">${inviteDetail.inviteCode}</div>`)
                                        let joinBtn=$("#join")
                                        let myPopover2=$("#myPopover2")
                                        myPopover2.hide()
                                        joinBtn.click(function (){
                                            showInviteCode(joinBtn,myPopover2)
                                        })
                                    }
                                }
                            }
                        })

                    }
                })
                //添加到购物车点击事件
                $("#addCart").click(function () {
                    $.ajax({
                        url: "/PDD/cart?method=addCart&pId=" + data.pId,
                        dataType: "json",
                        success: function (result) {
                            if (result.code === 401) {
                                alert(result.data)
                                window.location.href = "login.html"
                            } else {
                                window.location.href = "cartSuccess.html"
                            }
                        },
                        error: function (jqXHR, textStatus, errorThrown) {
                            alert(textStatus + ": " + errorThrown);
                        }
                    })
                })
                //增加数量点击事件
                $("#add").click(function () {
                    let num = $("#num")
                    if (parseInt(num.val()) < data.stock) {
                        num.val(parseInt(num.val()) + 1)
                    }
                })
                //减少数量点击事件
                $("#substract").click(function () {
                    let num = $("#num")
                    if (parseInt(num.val()) > 1) {
                        num.val(parseInt(num.val()) - 1)
                    }
                })
                //直接购买点击事件
                $("#buy").click(function () {
                    window.location.href = "order2.html?pId=" + pId + "&num=" + parseInt($("#num").val());
                })
                let favorite = $("#favorite")

                //收藏商品的图标显示与否(后台查数据)
                $.ajax({
                    url: "/PDD/product?method=getFavoriteByUidAndPid",
                    data: {
                        "pId": data.pId
                    },
                    dataType: "json",
                    success: function (data) {
                        if (data.code !== 401) {
                            if (data.code === 404) {
                                //未收藏
                                favorite.text("收藏")
                            } else {
                                //已收藏
                                favorite.attr("class", "btn btn-default")
                                favorite.text("已收藏")
                            }
                        } else {
                            window.location.href = "login.html"
                        }
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        alert(textStatus + ": " + errorThrown);
                    }
                })


                //收藏商品
                favorite.click(function () {
                    if (favorite.text() === "收藏") {
                        let isFavorite = 1
                        let pId = data.pId
                        $.ajax({
                            url: "/PDD/product?method=setAsFavorite",
                            data: {
                                "pId": pId,
                                "isFavorite": isFavorite
                            },
                            dataType: "json",
                            success: function (data) {
                                if (data.code === -1) {
                                    alert("收藏失败,请稍后再试")
                                } else {
                                    alert("收藏成功!")
                                    favorite.attr("class", "btn btn-default")
                                    favorite.text("已收藏")
                                }
                            },
                            error: function (jqXHR, textStatus, errorThrown) {
                                alert(textStatus + ": " + errorThrown);
                            }
                        })
                    }

                })
            }

        })

        function showInviteCode(joinBtn,myPopover2){

                let position = joinBtn.offset();  // 获取按钮位置
                let posX = position.left; // 计算弹出框位置的 X 坐标
                let posY = position.top+25;  // 计算弹出框位置的 Y 坐标
                myPopover2.css({top: posY, left: posX}).show(); // 设定弹出框位置并显示它

            $(document).mouseup(function(e) {  // 点击页面其它部分时，隐藏弹出框
                let container = myPopover2;
                if (!container.is(e.target) && container.has(e.target).length === 0) {
                    container.hide();
                }
            });
        }

        // //购物车点击事件
        // $("#addCart").click(function (){
        //     $(this).attr("href","/PDD/login.html")
        //     alert($(this).attr("href"))
        //     //向后台查询登录状态
        //     $.ajax({
        //         url:"/PDD/user?method=checkLoginState",
        //         type: "POST",
        //         dataType: "json",
        //         success:function (data){
        //             alert(data.code)
        //             if(data.code===404){
        //                 //未登录 跳转到登录页面
        //                 $(this).attr("href","/PDD/login.html")
        //             }else{
        //                 //已登录 跳转到购物车页面
        //                 $(this).attr("href","/PDD/cart.html")
        //             }
        //         }
        //     })
        // })
    })
</script>
</body>
</html>